package com.yin.forkjoin;

import java.util.concurrent.RecursiveTask;

/*
    求和计算
 */
public class ForkJoin extends RecursiveTask<Long> {

    private long start;
    private long end;

    private long temp = 10000L;

    public ForkJoin(long start, long end) {
        this.start = start;
        this.end = end;
    }


    // 计算方法
    @Override
    protected Long compute() {
        if ((end - start) < temp) {
            long sum = 0L;
            for (Long i = 0L; i <= 10_0000_0000 ; i++) {
                sum += i;
            }
            return sum;
        } else {
            long middle = (start + end) / 2;
            // 分支合并计算
            ForkJoin forkJoin = new ForkJoin(start, middle);
            forkJoin.fork(); // 拆分任务，把线程压入队列
            ForkJoin forkJoin2 = new ForkJoin(middle + 1, end);
            forkJoin2.fork(); // 拆分任务，把线程压入队列

            return forkJoin.join() + forkJoin2.join();
        }
    }
}
